package com.Service.impl;

import com.mapper.GroupActivityMapper;
import com.mapper.GroupJoinMapper;
import com.pojo.GroupActivityVO;
import com.Service.GroupService;
import com.pojo.GroupActivityVO;
import com.pojo.GroupJoin;
import com.pojo.GroupJoinVO;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class GroupServiceImpl implements GroupService {
    @Autowired
    private GroupJoinMapper groupJoinMapper;
    @Resource
    private GroupActivityMapper groupActivityMapper;
    @Override
    public List<GroupJoinVO> getGroupsByUser(Long userId) {
        return groupJoinMapper.selectByUserIdWithActivity(userId);
    }

    @Override
    public GroupActivityVO getGroupDetail(Long id) {
        return groupActivityMapper.selectDetailById(id);
    }

    @Override
    public void joinGroup(Long activityId, Long userId) {
        groupJoinMapper.insert(new GroupJoin(null, activityId, userId, new Date(), false));
    }

    @Override
    public void initiateGroup(Long activityId, Long userId) {
        GroupJoin existing = groupJoinMapper.findByActivityIdAndUserId(activityId, userId);
        if (existing != null) {
            throw new RuntimeException("您已参与该拼团活动，不能重复发起！");
        }

        GroupJoin groupJoin = new GroupJoin();
        groupJoin.setActivityId(activityId);
        groupJoin.setUserId(userId);
        groupJoin.setIsInitiator(true);
        groupJoin.setJoinedAt(new Date());

        groupJoinMapper.insert(groupJoin);
    }
}
